import numpy as np
import tool
import scipy.stats as stats
import matplotlib.pyplot as plt
from scipy.stats import pearsonr

plt.rcParams["font.sans-serif"] = ["SimHei"]  # 使用黑体
plt.rcParams["axes.unicode_minus"] = False  # 解决负号显示问题


def descriptive_statistics(np_array):
    stats_dict = {
        "均值": np.mean(np_array),
        "中位数": np.median(np_array),
        "众数": stats.mode(np_array, keepdims=True)[0][0],
        "标准差": np.std(np_array),
        "方差": np.var(np_array),
        "最小值": np.min(np_array),
        "最大值": np.max(np_array),
        "范围": np.max(np_array) - np.min(np_array),
        "第25百分位数": np.percentile(np_array, 25),
        "第75百分位数": np.percentile(np_array, 75),
        "四分位距": np.percentile(np_array, 75) - np.percentile(np_array, 25),
        "偏度": stats.skew(np_array),
        "峰度": stats.kurtosis(np_array),
        "样本大小": len(np_array),
    }
    for row in stats_dict:
        print(row, stats_dict[row])
    return stats_dict


def plot_distribution(np_array):
    plt.figure(figsize=(12, 6))

    # 绘制直方图
    plt.hist(np_array, bins=20, color="skyblue", edgecolor="black", density=True)
    plt.title("直方图")
    plt.xlabel("值")
    plt.ylabel("频率")

    # 绘制正态分布曲线
    mean = np.mean(np_array)
    std_dev = np.std(np_array)
    x = np.linspace(np.min(np_array), np.max(np_array), 100)
    plt.plot(
        x,
        stats.norm.pdf(x, mean, std_dev),
        color="red",
        linestyle="dashed",
        linewidth=2,
        label="正态分布",
    )
    plt.legend()

    plt.tight_layout()
    plt.show()


def check_normality(data, alpha=0.05):
    if len(data) < 5000:
        # Shapiro-Wilk Test
        shapiro_stat, shapiro_p = stats.shapiro(data)

        print(f"Shapiro-Wilk 检验: W={shapiro_stat}, p-value={shapiro_p}")

        if shapiro_p > alpha:
            print("数据可能符合正态分布")
        else:
            print("数据不符合正态分布")
    else:
        # 正态分布的均值和标准差
        mean = np.mean(data)
        std = np.std(data)

        # Kolmogorov-Smirnov Test
        ks_stat, ks_p = stats.kstest(data, "norm", args=(mean, std))

        print(f"Kolmogorov-Smirnov 检验: D={ks_stat}, p-value={ks_p}")

        if ks_p > alpha:
            print("数据可能符合正态分布")
        else:
            print("数据不符合正态分布")


def check_overall_correlation(threshold=0.5):
    """
    检查所有蔬菜品类的总销量与平均加成之间的总体相关性。

    参数:
    - data: 输入的 numpy 结构化数组，必须包含 'code', 'total_quantity', 'addition' 字段
    - threshold: 判断相关性的阈值，默认为 0.5

    返回:
    - bool: 如果总体相关性绝对值大于阈值，返回 True，否则返回 False
    """
    data = tool.get_np("normal_price.csv")
    unique_codes = np.unique(data["code"])

    # 初始化列表来存储每个品类的总销量和平均加成
    total_quantities = []
    average_additions = []

    for code in unique_codes:
        # 筛选出特定蔬菜品类的数据
        subset = data[data["code"] == code]

        # 计算总销量和平均加成
        total_quantity_sum = np.sum(subset["total_quantity"])
        average_addition = np.mean(subset["addition"])

        # 将结果添加到列表中
        total_quantities.append(total_quantity_sum)
        average_additions.append(average_addition)

    # 将列表转换为 NumPy 数组
    total_quantities = np.array(total_quantities)
    average_additions = np.array(average_additions)

    # 计算总销量与平均加成之间的相关性
    correlation, _ = pearsonr(total_quantities, average_additions)

    # 判断相关性是否超过阈值
    if abs(correlation) > threshold:
        print("相关")
    else:
        print("不相关")
    print(correlation)


if __name__ == "__main__":
    pass
    check_overall_correlation()
